# 创建时间:2023/3/18 21:35
# 创建人:天霄
# 计划 :SenjoTwintail
# 文件 :Login.py
# 基于 Python 3.8.2
# ========================================
# 登录页
# ========================================
from typing import Union
import pygame
from pygame.surface import Surface, SurfaceType

from Api import uiApi, savings
from BasePygame.Gamer import PageDict, SpriteCommon, change_image, load
from BasePygame.Public import flagBox
from PyGameUI.Use import soundBox
from PyGameUI.Use.AsyncGenerate import genAsync


class LoginPage(PageDict):
    """登录页面"""
    def __init__(self, touch):
        """登录页面"""
        bgsurface = change_image(uiApi.getUiPicture('loginbg')[0])
        super().__init__(bgsurface)
        self.login_start_cut = uiApi.getUiPicture('loginlayer', 'ui/login/res/start.png')
        login_start = SpriteCommon(*self.login_start_cut)
        self.login_start_size = login_start.image.get_size()
        self.add(login_start, 'start')
        self.touch = touch

    def __del__(self):
        for one in self.SurfaceDict:
            try:
                self.SurfaceDict.get(one).kill()
            except:
                continue
        super().__del__()

    def get(self, key):
        """获取图片"""
        if key not in self.SurfaceDict:
            raise KeyError(f'键”{key}“不存在！当前键：{self.SurfaceDict.keys()}')
        surface: Union[Surface, SurfaceType, SpriteCommon]
        surface = self.SurfaceDict[key]
        return surface

    def drawAll(self):
        """绘制所有图像"""
        self.draw_bg()
        self.draw_others()
        if self.is_touch_start() and flagBox.clicked:
            load.loading()
            flagBox.clickable = True
            flagBox.herePageClickTo = 'home'
            flagBox.where_in = 'buttonStart'
            savings.record_loginTime()

    def draw_bg(self):
        """绘制背景"""
        self.screen.blit(self.bg, (0, 0))

    def draw_others(self):
        """绘制背景之外的元素"""
        if self.is_touch_start():
            self.scale_start()
        else:
            self.resize_start()
        halfRect = pygame.Rect(*self.screen_sizeRect.midleft, self.screen_sizeRect.w, self.screen_sizeRect.h / 2)
        start: SpriteCommon = self.get('start')
        startRect = start.rect
        startRect.center = halfRect.center
        self.screen.blit(start.image, startRect)

    def scale_start(self):
        """放大1.2倍"""
        self.SurfaceDict['start'].kill()
        start_new = SpriteCommon(*self.login_start_cut, 0, 1.2)
        self.set('start', start_new)

    def resize_start(self):
        """还原start大小"""
        self.SurfaceDict['start'].kill()
        start_new = SpriteCommon(*self.login_start_cut)
        self.set('start', start_new)

    def is_touch_start(self):
        """判断鼠标精灵是否与开始按钮相撞"""
        start: SpriteCommon = self.get('start')
        return pygame.sprite.collide_mask(self.touch, start)